package purchaseService

import (
	"errors"
	"go-ddd-ecommerce/internal/domain/order"
	"go-ddd-ecommerce/internal/domain/product"
	"go-ddd-ecommerce/internal/domain/user"
)

// PurchaseService 领域服务-用来处理购买相关的多个聚合根
// 在领域服务这里会编写一些领域编排的业务逻辑,每个聚合根会执行它自己的业务逻辑
type PurchaseService struct{}

func NewPurchaseService() *PurchaseService {
	return &PurchaseService{}
}

// Purchase 购买业务逻辑
func (p *PurchaseService) Purchase(
	user *user.User,
	product *product.Product,
	quantity int,
) (*order.Order, error) {
	// 1. 验证业务规则
	if err := p.validatePurchase(user, product, quantity); err != nil {
		return nil, err
	}

	// 2. 执行业务操作
	if err := product.DeductStock(quantity); err != nil {
		return nil, err
	}

	totalAmount := product.Price * float64(quantity)
	if err := user.SubBalance(totalAmount); err != nil {
		return nil, err
	}

	// 3. 创建订单（这是购买的核心业务结果）
	newOrder, err := order.NewOrder(user.ID, product.ID, quantity, product.Price)
	if err != nil {
		return nil, err
	}

	return newOrder, nil
}

// validatePurchase 业务规则验证
func (s *PurchaseService) validatePurchase(user *user.User, product *product.Product, quantity int) error {
	// 业务规则1：商品必须可购买
	if product.Stock <= 0 {
		return errors.New("商品已售罄")
	}

	// 业务规则2：购买数量不能超过库存
	if quantity > product.Stock {
		return errors.New("购买数量超过库存")
	}

	// 业务规则3：用户余额必须足够
	totalAmount := product.Price * float64(quantity)
	if user.Balance < totalAmount {
		return errors.New("用户余额不足")
	}

	// 业务规则4：单次购买数量限制
	if quantity > 10 {
		return errors.New("单次购买数量不能超过10件")
	}

	return nil
}
